<?php

namespace control;
class productErpClass extends adIndexClass
{
    private const         page = 'productErp'; # 权限
    private const         table = 'aa_product'; # 数据表
    private const         title = '产品数据';
    private const         applyOption = ['1' => '已使用', '0' => '未使用'];
    private const         bindOption = ['1' => '已绑定', '0' => '未绑定'];


    /*列表页-查询条件*/
    public function home()
    {
        $html =
            text(["name" => "plan_no", "title" => "计划号"]) .
            text(["name" => "batch", "title" => "发动机流水号"]) .
            text(['name' => "classify", "title" => "分类",]) .
            text(['name' => "brand", "title" => "品牌",]) .
            text(["name" => "text", "title" => "状态描述"]) .
            text(["name" => "iot_no", "title" => "AI物联码"]) .
            text(["name" => "production_date", "laydate" => ['type' => 'date', 'range' => '~'], "title" => "生产日期"]) .
            text(["name" => "apply_date", "laydate" => ['type' => 'date', 'range' => '~'], "title" => "使用日期"]) .
            text(["name" => "state_no", "title" => "状态号"]) .
            text(["name" => "material_name", "title" => "物料名称"]) .
            select(["name" => "apply_state", "title" => "使用状态", 'class' => "select", "option" => self::applyOption]) .
            select(["name" => "bind_state", "title" => "绑定状态", 'class' => "select", "option" => self::bindOption]) .
            selectMultiple(array('table' => 'staff', "title" => '创建人', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'createId'));
        return $this->homeFun($this->search($html));
    }

    public function homeSearch(): bool|string
    {
        $like = [
            "plan_no"   => $this->post('plan_no'),
            "batch"     => $this->post('batch'),
            "classify"  => $this->post('classify'),
            "text"      => $this->post('text'),
            "ai_iot_no" => $this->post('iot_no'),
            "brand" => $this->post('brand'),

            "state_no"      => $this->post('state_no'),
            "material_name"=> $this->post('material_name'),
        ];
        //全等查询数组
        $equal = array(
            "apply_state" => $this->post('apply_state'),
            "bind_state"  => $this->post('bind_state'),
            "createId"    => $this->post('createId'),
            'coid'        => self::$coid,
        );
        $and = "";
        if ($this->post('production_date')) {
            //单据日期
            $and .= self::timeComparison($this->post('production_date'), 'date', 'production_date');
        }

if ($this->post('apply_date')) {
    //单据日期
    $and .= self::timeComparison($this->post('apply_date'), 'date', 'apply_date');
}

//获取查询结果
$where = search(["like" => $like, "=" => $equal]) . $and;
// 查询自己
if ($this->power(self::page, "seeAll")) {
    $where .= "  ";
} else if ($this->power(self::page, "see")) {
    $where .= " and createId = '" . self::$stid . "' ";
}
$page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
$_SESSION[self::page]['sql'] = $page['sql'];
//获取表头
$checkAll = $this->checkAll("listForm", "listId");
//
$tr[] = [$checkAll, '计划号', '发动机流水号', '发动机批次号', '状态号', '分类','品牌', '物料名称', '单位',
    '状态描述', 'AI物联码', '生产日期', '使用日期', '充值时间', '绑定状态', '使用状态', '创建人'];
if (para('showProductTime') == "否") {
    unset($tr[0][9]);
}
//获取记录
$url = root . "control/adIndex.php?cla=" . self::page;

foreach ($page['array'] as $index => $array) {
    //列表控件
    $dominate = array(
        "box" => array("name" => "listId", "value" => $array['id']),
        'edit' => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'$array[id]'})"),
    );
    $dominateHtml = $this->dominate($dominate);

    if ($array['bind_state'] == 1) {
//        $dominateHtml = "<span></span>";
$dominateHtml="<label class=\"listCheckbox\"><input name=\"listId[]\" type=\"checkbox\" value=\"{$array['id']}\"><span></span></label>";
    }
    $tr[] = [$dominateHtml, $array['plan_no'], $array['batch'], $array['newBatch'], $array['state_no'], $array['classify'],$array['brand'],
        $array['material_name'], $array['unit'], $array['text'], $array['ai_iot_no']
        , $array['production_date'], $array['apply_date'], $array['recharge_time'], self::bindOption[$array['bind_state']], self::applyOption[$array['apply_state']], self::findStaff($array['createId'])];
    if (para('showProductTime') == "否") {
        unset($tr[$index + 1][9]);
    }
}
//控件
$button = "";
if ($this->power(self::page, "edit")) {
    $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
}
if ($this->power(self::page, "del")) {
    $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'del'})\">删除</span>\n";
}
if ($this->power(self::page, "import")) {
    $button .=
        importTemplateClass::importTemplateButton(self::page) .
        $this->upButton(array("title" => "导入", "fun" => "importData"));
}
if ($this->power(self::page, "export")) {
    $button .= "  <a href='" . root . "control/adIndex.php?cla=" . self::page . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
}
if ($this->power(self::page, "setUp")) {
    $button .= "<span onclick=\"layer('" . self::page . "','setUp',{})\" class='spanButton'>设置</span>\n";
}
if ($this->power(self::page, "edit")) {
    $button .= "<span onclick=\"un_bind()\" class='spanButton'>解绑</span>\n";
}
$button.="<a href='javascript:' onclick='printQrcode(2)'><span class='spanButton'>唛头</span></a>";
$button.="<a href='javascript:' onclick='printQrcode(1)'><span class='spanButton'>二维码</span></a>";
//返回
$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
$json['html'].=<<<eof
<script>
function printQrcode(type) {
    get_checked_box1('productErp','printQRPage','listForm',type)
    //  layer('productErp', 'printQrcode', {batch: vals});
    // alert('6666')
}
function un_bind() {
  var ids=get_checked_box_val('listForm');
  if (!ids){
      msg('请选择数据')
      return;
  }else {
         layer('productErp', 'un_bind', {ids: ids});
  }
}
</script>
eof;
return json_encode($json, 320);
}

public function printQrcode(){
    $root = root;
    $content = '';
    $listArr = explode(',', $this->post('listId'));
    $type=$this->post('type')??1;
    foreach (array_unique($listArr) as $id){
        //材料信息
        $material_sku = query(self::table, "id = '$id'");
    $batch = $material_sku['batch'];
        $parameter = urlencode(para("AICodeUrl") . "?batch=" . $batch);
        $content .= <<<efo
                               <div class="qr-content" style="display: none">
                                     <img alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
                                     <div class="qr-content-barcode">{$batch}</div>
                                     <input name='batch[]' type='hidden' value='$batch'>
                               </div><br>
efo;
}
    $print = "保存";
    $html = <<<efo
                <form style="display: none" name="printForm" target="_blank" method="post" action="{$root}control/adIndex.html?cla=productErp&fun=printQRPage">
                <div class="printEditPage">
                           {$content}
                </div>
                <div style="display: flex;flex-direction: row;justify-content: space-around">
                <div><input type="radio" name="p_type" value="1" checked>样式一</div>
                <div><input type="radio" name="p_type" value="2">样式二</div>
                
                
</div>
                <div style='width: 100%;margin-top: 40px;text-align: center;'>
                    <input type='submit' class='button' value='{$print}' ">
                </div>
                </form>

efo;

    return $this->layer(array("title" => "设备码", "height" => 400, "width" => 400, "html" => $html . $this->style()));
}

public function un_bind(){
        $ids=$this->post('ids')??'';
        if (!$ids){
            return json_encode(['warn'=>'参数缺失'], 320);
        }
        $ids=explode(',',$ids);
        $delId=implode("','",$ids);
    try {
        update(['table' => "aa_product",
            "where" => "id in ('{$delId}')",
            "field" => [
                "ai_iot_no"       => "",
                "production_date" => "",
                "bind_state"      => 0,
                "apply_date"      => null,
                "apply_state"      => 0
            ]
        ]);
    }catch (\Exception $e){
        return json_encode(['warn'=>'参数缺失'], 320);
    }

    return json_encode(['warn'=>'操作成功'], 320);

}
public function style(): string
{
    return <<<efo
<style>
.printEditPage{width: 100%;height: auto;overflow: auto; display: flex;justify-content:center;flex-wrap: wrap}
.printEditPage>ul>li{float: left;margin: 5px;padding: 5px}
.qr-content{width: 240px;height: 180px;background-color: #F0F8FA;text-align: center;margin: 10px;padding: 10px;overflow: auto}
.qr-content img{width: 120px}
.qr-content-barcode{font-size: 15px;font-weight: bold;margin: 5px 0}
.qr-content-bottom{word-wrap:break-word;}
.qr-num{width: 250px;margin: 10px}
</style>
efo;
}

public function printQRPage(): string
{
    $listArr = explode(',', $this->get('listId'));
    $type=$this->get('type');
    $root = root;
    $content = '';
    $ids=implode("','",array_unique($listArr));
    $lists=find(['table'=>self::table,"where"=>"id in ('{$ids}') order by batch asc"]);
    foreach ($lists['array'] as $info){
        $id=$info['id'];
//    $info = query(self::table, "id = '$id'");
    $num=sqlNum(self::table,"newBatch = '{$info['newBatch']}'");
    $num=$num?$num:1;
        $batch=$info['batch'];
    $text=$info['text']??'';
    $name=$info['material_name']??'';
        //材料信息
        $parameter = urlencode(para("AICodeUrl") . "?batch=" . $batch);
        if ($type==1){
            foreach (['1','2'] as $v){
                $content .= <<<efo
    <div style="width: 200px;height: 80px;padding: 0;overflow: hidden;white-space: nowrap;">
                <div style="width:100px;float: left;padding-top: 5px;padding-left: 2px"> 
                <div style="white-space: nowrap;overflow: hidden;height: 20px;width: 98px">$name</div>
                 <div  style="white-space: nowrap;overflow: hidden;margin-top:5px;height: 20px;width: 98px">$batch</div>
                </div>
               <div style="float: right;width:80px;height: 80px;padding: 0 ">
                <img height="80px" alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
</div>
    </div>

efo;
            }

        }else{
            $content.=<<<efo
    <div style="width: 350px;border: 1px solid;padding: 10px;height: 400px;margin: auto;margin-top: 20px">
                <div style="width:200px;float: left;height: 100px;padding-left: 10px"> 
                <h1 >摩畅联</h1>
                 <h2 style="margin-top: 20px">$name</h2>
                </div>
               <div style="float: right;width:100px;margin-top: 30px;height: 100px ">
                <img height="100px" alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
</div>
    <div style="overflow: hidden;padding: 10px;width: 100%;height: 80px;margin-top:10px;display: block;border-top: 1px solid;border-bottom: 1px solid;border-left: 1px solid;border-right: 1px solid"> $text </div>
    <div style="padding: 10px;width: 100%;height: 30px;line-height: 30px;margin-top:20px;display: block;border-top: 1px solid;border-bottom: 1px solid;border-left: 1px solid;border-right: 1px solid">流水号:$batch</div>
    
    <div style="width: 200px;margin-top: 10px;float: left;padding-left: 10px">服务商：齐配配</div>
    <div align="width: 200px;margin-top: 10px">本批数量：$num</div>
    </div>
efo;
        }}

    $print = new printClass();
    return $print->makePdf($content,$type);
    }
/**
 * 导出
 */

public
function exportData()
{
    if (!$this->power(self::page, 'export')) {
        $_SESSION['warn'] = '你还没有导出的权限';
    } else {
        $data = [];
        $sql = $_SESSION[self::page]['sql'];
        $title = ["计划号", "发动机批次号", "发动机流水号", "状态号", "物料名称", "分类","品牌", "主单位", "状态描述", "AI物联码", "生产日期", "使用日期", "充值时间", "绑定状态", "使用状态", "创建人"];
        $result = self::sqlFind($sql);
        if (is_array($result)) {
            foreach ($result as $array) {
                $data[] = [$array['plan_no'], $array['batch'], $array['newBatch'], $array['state_no'], $array['classify'],
                    $array['material_name'], $array['brand'], $array['unit'], $array['text'], $array['ai_iot_no']
                    , $array['production_date'], $array['apply_date'], $array['recharge_time'], self::bindOption[$array['bind_state']], self::applyOption[$array['apply_state']], self::findStaff($array['createId'])];

            }
        }
        $text = $this->control['name'] . "导出了产品数据";
        $this->logText(["type" => self::page, "text" => $text]);
        $this->excelOut($title, $data, "产品数据.xlsx");
    }
    header("Location:" . getenv("HTTP_REFERER"));
    exit(0);
}

/**
 * 下载模板
 */
public
function downloadModel()
{
    if (!$this->power(self::page, 'edit')) {
        $_SESSION['warn'] = '你还没有编辑的权限';
    } else {
        //
//        $title = ['计划号', '发动机批次号', '发动机流水号', '状态号', '物料名称', '分类', '单位', '状态描述'];
        $title = ['计划号', '发动机批次号', '发动机流水号','品牌', '物料名称', '分类', '单位', '状态描述'];
        $data[] = ['s001', 's001', 's001', '品牌001', '物料名称','分类', '单位', '状态描述'];
        $text = $this->control['name'] . "下载了产品数据导入模板";
        $this->logText(["type" => self::page, "text" => $text]);
        $this->excelOut($title, $data, '产品数据导入模板.xlsx');
        exit(0);
    }
    header("Location:" . getenv("HTTP_REFERER"));
}

/*数据导入分析*/

public
function importData()
{
    if (!$this->power(self::page, 'edit')) {
        $_SESSION['warn'] = '你还没有编辑的权限';
    } else {
        $data = $this->importHead();
        $x = 0;
        $text = '';
        foreach ($data as $i => $row) {
            if ($i > 0) {
                $cell = formSubArray($row);
                $field = [
                    'id' => self::getId(),
                    'coid' => self::$coid,
                    'plan_no' => $cell[0],
                    'batch' => $cell[2],
                    'newBatch' => $cell[1],
                    'state_no' => '',
                    'material_name' => $cell[4],
                    'classify' => $cell[5],
                    'unit' => $cell[6],
                    'text' => $cell[7],
                    'brand' => $cell[3]??'',
                    'createId' => self::$stid,
                    'updateTime' => $this->time,
                    'time' => $this->time,

                ];
                $annotation = [
                    'batch' => '发动机流水号',
                ];
                $rules = [
                    'batch' => 'required',
                ];
                // 校验是否符合规则
                $vt = new \verify();
                $text = "第【{$i}】行：";
                $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                if ($result === false) {
                    $text .= $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                } elseif (self::total(['table' => self::table, 'where' => " and batch = '$field[batch]' and coid = '" . self::$coid . "'"]) > 0) {
                    $text .= "【发动机流水号】已存在";
                } else {
                    $warn = self::insert(["table" => self::table, "field" => $field,]);
                    if (in_array($warn, ["新增成功", "更新成功"])) {
                        $x++;
                        $text .= self::title . "【{$cell[0]}】导入成功<br>";
                    } else {
                        $text .= self::title . "【{$cell[0]}】导入失败：编辑失败<br>" . $warn;
                    }
                }
            }
        }
        $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
        $this->logText(["type" => self::page, "text" => $text]);
        $warn = "成功导入" . $x . "条数据，详情请查看日志！";
        $_SESSION['warn'] = $warn;
    }
    header("Location:" . getenv("HTTP_REFERER"));
    exit(0);
}

/**
 */
public
function setUp(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "生产时间显示：" => radio(["name" => "isShow", 'value' => ['是', '否'], "checked" => para("showProductTime")]),
            ),
        ), 'formTwo' => 'listForm'));
        //返回
        return $this->layer(array("title" => "设置", "height" => 165, "width" => 500, "html" => $html));
    }

    /**
     */
    public function setUpEdit(): bool|string
    {


        $field = [
            'paValue' => $this->post('isShow'),
        ];
        $json['warn'] = update(array('table' => "para", 'field' => $field, 'where' => " paid ='showProductTime'"));
        if (in_array($json['warn'], ["新增成功", "更新成功"])) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了生产时间是否展示的状态为【{$this->post('isShow')}】";
            $this->logText(["type" => self::page, "text" => $text]);
            //返回
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*基本资料-弹出层*/
    public function edit(): string
{

    $id = $this->post('id') ?: suiji();
    $info = query(self::table, " id = '" . $id . "' ");
    $html = $this->layerEdit(array(
        "table" => array(
            array(
                "计划号：" => text(array("name" => "plan_no", "class" => "width350", "value" => $info['plan_no'])),
            ),
            array(
                must . "发动机流水号：" => text(array("name" => "batch", "class" => "width350", "value" => $info['batch'])),
            ),
            array(
                "发动机批次号：" => text(array("name" => "newBatch", "class" => "width350", "value" => $info['newBatch'])),
            ),
            array(
                "状态号：" => text(array("name" => "state_no", "class" => "width350", "value" => $info['state_no'])),
            ),
            array(
                "物料名称：" => text(array("name" => "material_name", "class" => "width350", "value" => $info['material_name'])),
            ),
            array(
                "分类：" => text(array("name" => "classify", "class" => "width350", "value" => $info['classify'])),
            ),
            array(
                "单位：" => text(array("name" => "unit", "class" => "width350", "value" => $info['unit'])),
            ),
            array(
                "品牌：" => text(array("name" => "brand", "class" => "width350", "value" => $info['brand'])),
            ),
            array(
                "状态描述：" => textarea(array("name" => "text", "class" => "width350", "value" => $info['text'])),
            )
        ),
    ));
    //返回
    return $this->layer(array("title" => "新增", "height" => 500, "width" => 700, "zindex" => 98, "html" => $html));
}


    /*异步处理*/
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?? self::getId();
        $field = [
            'plan_no' => $this->post('plan_no'),
            'batch' => $this->post('batch'),
            'newBatch' => $this->post('newBatch'),
            'state_no' => $this->post('state_no'),
            'material_name' => $this->post('material_name'),
            'classify' => $this->post('classify'),
            'unit' => $this->post('unit'),
            'text' => $this->post('text'),
            'brand' => $this->post('brand'),
        ];
        $annotation = [
            'batch' => '发动机批次号',
        ];
        $rules = [
            'batch' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (self::total(['table' => self::table, 'where' => " and id != '$id' and batch = '$field[batch]' and coid = '" . self::$coid . "'"]) > 0) {
            $json['warn'] = "【发动机批次】已存在";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, [
                "id" => $id,
                'coid' => self::$coid,
                'createId' => self::$stid,
                'updateTime' => $this->time,
                'time' => $this->time
            ]);
            $json['warn'] = self::insert(["table" => self::table, "field" => $field]);
        } else {

            $json['warn'] = self::update(["table" => self::table, "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }

        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个" . self::title . "：" . $field['batch'] . ",ID：" . $id;
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.php?cla=' . self::page . '&fun=home';
        }
        //返回
        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = $append = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '是否确认删除所选数据?';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.php?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'append' => $append,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            $ids=implode("','",$array);
            $lst=sqlNum(self::table,"id in ('$ids') and bind_state = 1");
          if ($lst){
              $json['warn'] = '已绑定数据不能删除!';
              return json_encode($json, 320);
          }
            foreach ($array as $id) {
                delete(array("table" => self::table, "where" => " id = '$id' "));
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.php?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


}